//
//  HomeCell3.m
//  Tunnel
//
//  Created by wbb on 2025/6/3.
//

#import "HomeCell3.h"
#import "HyCategories.h"
#import "HyChartsBarDemoCursor.h"
#import "YXJCVC.h"
#import "HyCharts.h"
#import "BottomPopupView.h"
#import <WebKit/WebKit.h>

@interface HomeCell3 ()<WKNavigationDelegate>

@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) NSArray * titles;
@property (nonatomic, copy) NSArray * values;
@property (nonatomic, strong) NSNumber * maxValue;

@end

@implementation HomeCell3

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    
    
    //    [oneChartView mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.edges.offset(10);
    //    }];
    
    [self setDataSource:@[] titles:@[]];
}
- (void)cellWithData:(id)data {
    [super cellWithData:data];
    
    NSArray *arr = (NSArray *)data;
    NSMutableArray *values = [NSMutableArray arrayWithCapacity:0];
    NSMutableArray *titles = [NSMutableArray arrayWithCapacity:0];
    self.maxValue = 0;
    [arr enumerateObjectsUsingBlock:^(NSDictionary *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [values addObject:obj[@"num"]];
        NSString *devName = [NSString stringWithFormat:@"%@",obj[@"devName"]?:@""];
        
//        if(devName.length>5) {
//            devName =[NSString stringWithFormat:@"%@\n%@",[devName substringToIndex:5],[devName substringFromIndex:5]];
//        }
        [titles addObject:devName];
        
        self.maxValue =    [self roundUpToNearestTen:MaxNumber(obj[@"num"], self.maxValue)] ;
    }];
    
    [self.allSysBtn setTitle:[NSString stringWithFormat:@"%@",self.selectItem3?:@"全部系统"] forState:UIControlStateNormal];
    
    
    [self setDataSource:values titles:titles];
    
    [self.allSysBtn layoutButtonWithEdgeInsetsStyle:TYButtonEdgeInsetsStyleRight imageTitleSpace:5];
    self.allSysBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 5);
    [self.allSysBtn sizeToFit];
    [self.allSysBtn layoutIfNeeded];
    
}
- (void)setDataSource:(NSArray *)values titles:(NSArray *)titles {
    _titles = titles;
    _values = values;
    if(self.webView) {
        [self.webView reload];
        return;
    }
    
    // 初始化WKWebView配置
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    
    // 创建WKWebView
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(15, 10, kSCREEN_WIDTH -30 - 24, ScaleNum(162)) configuration:config];
    self.webView.navigationDelegate = self;
//    self.webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.bottomView addSubview:self.webView];
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.bottom.offset(0);
    }];
    self.webView.scrollView.scrollEnabled = NO;
    // 加载本地HTML文件（确保HTML文件已添加到项目中，并勾选了对应的target）
    NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"BarCharts" ofType:@"html"];
    NSURL *fileURL = [NSURL fileURLWithPath:htmlPath];
    NSURLRequest *request = [NSURLRequest requestWithURL:fileURL];
    [self.webView loadRequest:request];
    
    //    UIView *oneChartView =  [self oneChartBarViewWithFrame:CGRectMake(15, 10, kSCREEN_WIDTH -30 - 24, ScaleNum(162))];
    //    [self.bottomView addSubview:oneChartView];
}

- (UIView *)oneChartBarViewWithFrame:(CGRect)frame {
    
    UIView *contentView = [[UIView alloc] initWithFrame:frame];
    contentView.backgroundColor = UIColor.whiteColor;
    contentView.layer.cornerRadius = 5;
    contentView.layer.borderWidth = 1.0;
    contentView.layer.borderColor = UIColor.groupTableViewBackgroundColor.CGColor;
    contentView.clipsToBounds = NO;
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, CGRectGetWidth(frame) - 20, 0)];
    titleLabel.text = @"";
    titleLabel.font = [UIFont systemFontOfSize:17];
    titleLabel.textColor = UIColor.darkTextColor;
    [contentView addSubview:titleLabel];
    
    HyChartBarView *chartBarView =  [[HyChartBarView alloc] initWithFrame:CGRectMake(10, CGRectGetMaxY(titleLabel.frame) + 15, CGRectGetWidth(titleLabel.frame), CGRectGetHeight(frame) - CGRectGetMaxY(titleLabel.frame) - 25)];
    [contentView addSubview:chartBarView];
    
    chartBarView.contentEdgeInsets = UIEdgeInsetsMake(0, 35, 35, 10);
    chartBarView.pinchGestureDisabled = YES;
    // 自定义游标
    HyChartsBarDemoCursor *cursor = HyChartsBarDemoCursor.new;
    cursor.showView = chartBarView;
    [chartBarView resetChartCursor:cursor];
    kWEAK_SELF
    // 配置坐标轴
    [[chartBarView.dataSource.axisDataSource configXAxisWithModel:^(id<HyChartXAxisModelProtocol>  _Nonnull xAxisModel) {
        xAxisModel.topXaxisDisabled = NO;
        [[[[xAxisModel configNumberOfIndexs:3] configAxisGridLineInfo:^(id<HyChartAxisGridLineInfoProtocol>  _Nonnull axisGridLineInfo) {
            axisGridLineInfo.axisGridLineType = HyChartAxisLineTypeNone;
        }] configBottomXAxisInfo:^(id<HyChartXAxisInfoProtocol>  _Nonnull xAxisInfo) {
            //            xAxisInfo.rotateAngle = - M_PI_4;
            xAxisInfo.axisTextFont = [UIFont systemFontOfSize:14];
            xAxisInfo.displayAxisZeroText = NO;
        }] configTopXAxisInfo:^(id<HyChartXAxisInfoProtocol>  _Nonnull xAxisInfo) {
            xAxisInfo.autoSetText = NO;
            xAxisInfo.axisLineWidth = 1;
            xAxisInfo.axisLineColor = UIColor.groupTableViewBackgroundColor;
        }];
    }] configYAxisWithModel:^(id<HyChartYAxisModelProtocol>  _Nonnull yAxisModel) {
        [[[yAxisModel configNumberOfIndexs:5] configYAxisMaxValue:^NSNumber * _Nonnull{
            return weakSelf.maxValue;
        }] configLeftYAxisInfo:^(id<HyChartYAxisInfoProtocol>  _Nonnull yAxisInfo) {
            yAxisInfo.axisTextFont = [UIFont systemFontOfSize:14];
            yAxisInfo.axisTextPosition = HyChartAxisTextPositionBinus;
            yAxisInfo.axisLineType = HyChartAxisLineTypeNone;
            yAxisInfo.displayAxisZeroText = NO;
        }];
    }];
    
    
    // 配置图表信息
    [chartBarView.dataSource.configreDataSource configConfigure:^(id<HyChartBarConfigureProtocol>  _Nonnull configure) {
        configure.width = 10;
        configure.autoMargin = YES;
        [configure configBarConfigureAtIndex:^(NSInteger index, id<HyChartBarOneConfigureProtocol>  _Nonnull oneConfigure) {
            oneConfigure.fillColor = [UIColor colorWithRed:34/255.0 green:108/255.0 blue:254/255.0 alpha:1];// [UIColor colorFromGradientWithColors:@[[UIColor colorWithRed:34/255.0 green:108/255.0 blue:254/255.0 alpha:1],[UIColor colorWithRed:34/255.0 green:108/255.0 blue:254/255.0 alpha:0.2]] locations:@[@0,@1] position:0.5];
        }];
    }];
    
    NSArray<NSNumber *> *valus = self.values;//@[@42256, @25550, @12345, @10000, @9854, @8883, @6588, @3589, @888];
    NSArray<NSString *> *titles = self.titles;//@[@"美国", @"英国", @"意大利", @"韩国", @"西班牙", @"日本", @"法国", @"德国", @"巴西"];
    
    
    
    
    
    // 配置数据
    [[chartBarView.dataSource.modelDataSource configNumberOfItems:^NSInteger{
        return valus.count;
    }] configModelForItemAtIndex:^(id<HyChartBarModelProtocol>  _Nonnull model, NSInteger index) {
        model.text = titles[index];
        model.values = @[valus[index]];
        // 自定义数据
        NSDictionary *dict = @{@"colors" : @[[UIColor colorWithRed:34/255.0 green:108/255.0 blue:254/255.0 alpha:1]]};
        model.exData = dict;
    }];
    
    [chartBarView setNeedsRendering];
    //    chartBarView.dataSource.configreDataSource.configure.edgeInsetStart = 10;
    
    return contentView;
}
- (NSNumber *)roundUpToNearestTen:(NSNumber *)number1 {
    NSInteger number = [number1 integerValue];
    // 计算除以10的余数
    NSInteger remainder = number % 10;
    if (remainder == 0) {
        // 本身是10的倍数，直接返回
        return @(number);
    } else {
        // 向上取整到下一个10的倍数
        return @(number + (10 - remainder));
    }
}
- (IBAction)more:(UIButton *)sender {
    
    YXJCVC *vc = [[YXJCVC alloc] init];
    [[WDGlobal getCurrentViewController].navigationController pushViewController:vc animated:NO];
}

- (IBAction)allSysClick:(UIButton *)sender {
    
    [self showPickerPopup];
}


- (void)showPickerPopup {
    // 定义选项数组
    NSMutableArray * array = [NSMutableArray array];
    for (NSDictionary * dict in self.systemDictionaryList) {
        [array addObject:dict[@"propertyName"]];
    }
    
    // 创建底部弹出选择器（默认选中第0项）
    BottomPopupView *popup = [BottomPopupView pickerPopupWithTitle:@"请选择"
                                                             items:array
                                                     selectedIndex:0];
    
    // 显示弹出框
    kWEAK_SELF;
    [popup showInViewController:[WDGlobal getCurrentViewController] animated:YES completion:^(NSInteger selectedIndex, NSString *selectedItem) {
        NSLog(@"%@-%d",selectedItem,selectedIndex);
        if (selectedIndex >= 0) {
            [weakSelf.allSysBtn setTitle:[NSString stringWithFormat:@"%@",selectedItem] forState:UIControlStateNormal];
            if(weakSelf.cellBlock3){
                weakSelf.cellBlock3( selectedItem);
            }
            
        } else {
            //            self.selectedLabel.text = @"取消选择";
        }
    }];
}

#pragma mark - WKNavigationDelegate

// 网页加载完成后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    // 准备要传递给网页的数据
    //    NSArray *xData = @[@"衬衫", @"羊毛衫", @"雪纺衫", @"裤子", @"高跟鞋", @"袜子", @"连衣裙", @"外套"];
    //    NSArray *yData = @[@5, @20, @36, @10, @15, @25, @30, @18];
    NSLog(@"%@,%@",self.titles,self.values);
    // 将OC数组转换为JSON字符串
    NSString *xJsonStr = [WDGlobal convertArrayToJsonString:self.titles];
    NSString *yJsonStr = [WDGlobal convertArrayToJsonString:self.values];
    
    if (xJsonStr && yJsonStr) {
        // 构建JavaScript代码
        NSString *jsCode = [NSString stringWithFormat:@"updateChart(%@, %@);", xJsonStr, yJsonStr];
        
        // 执行JavaScript代码
        [webView evaluateJavaScript:jsCode completionHandler:^(id _Nullable result, NSError * _Nullable error) {
            if (error) {
                NSLog(@"调用JavaScript失败: %@", error.localizedDescription);
            } else {
                NSLog(@"数据已成功传递到网页");
            }
        }];
    } else {
        NSLog(@"JSON转换失败");
    }
}
@end
